package com.maikang.exammall.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.maikang.exammall.exception.JpaConverterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.persistence.AttributeConverter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
public class JpaConverterStringListJson implements AttributeConverter<List<String>, String> {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public String convertToDatabaseColumn(List<String> attribute) {
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            throw new JpaConverterException("failed to convert List of String to Json String");
        }
    }

    @Override
    public List<String> convertToEntityAttribute(String dbData) {
        try {
            if (!StringUtils.hasLength(dbData)) {
                return null;
            }
            String[] strings = objectMapper.readValue(dbData, String[].class);
            return Arrays.asList(strings);
        } catch (IOException e) {
            throw new JpaConverterException("failed to convert Json String to List of String", e);
        }
    }
}
